# Contributor: Borys Zhukov <mp5@mp5.im>
# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Maintainer: omni <omni+alpine@hack.org>
pkgname=ocaml
pkgver=4.14.0
pkgrel=0
pkgdesc="Main implementation of the Caml programming language"
url="https://ocaml.org/"
arch="all !riscv64" # hangs forever at final build step
license="LGPL-2.1-or-later-WITH-linking-exception"
depends="$pkgname-runtime=$pkgver-r$pkgrel gcc"
makedepends="gdbm-dev libc-dev ncurses-dev zlib-dev binutils-dev"
subpackages="
	$pkgname-doc
	$pkgname-dev
	$pkgname-ocamldoc
	$pkgname-compiler-libs:_compiler_libs
	$pkgname-runtime
	"
source="https://caml.inria.fr/pub/distrib/ocaml-${pkgver%.*}/ocaml-$pkgver.tar.gz"

# 32bit archs
case "$CARCH" in
armv7|armhf|x86) options="$options textrels" ;;
esac

build() {
	./configure \
		--prefix /usr \
		--bindir /usr/bin \
		--libdir /usr/lib/ocaml \
		--mandir /usr/share/man \
		CC="${CC:-gcc}" \
		AS="${CC:-gcc} -c" \
		ASPP="${CC:-gcc} -c"
	make world.opt
}

check() {
	make ocamlopt
	make ocamltest
	make tests
}

package() {
	make DESTDIR="$pkgdir" install

	install -Dm644 LICENSE "$pkgdir"/usr/share/licenses/$pkgname/LICENSE
	install -Dm644 Changes "$pkgdir"/usr/share/doc/$pkgname/Changes

	cd "$pkgdir"

	# Remove annotation files and sources.
	find usr/lib/ocaml \
		\( -name '*.cmt' -o -name '*.cmti' -o -name '*.ml' \) \
		-a -delete

	# To be consistent with other binaries.
	mv usr/bin/ocamldoc usr/bin/ocamldoc.byte
	ln -s ocamldoc.opt usr/bin/ocamldoc
}

dev() {
	pkgdesc="OCaml bytecode executables"

	_submv 'usr/bin/*.byte'
}

ocamldoc() {
	pkgdesc="Documentation generator for OCaml"
	depends="$pkgname=$pkgver-r$pkgrel"
	replaces="$pkgname"  # for backward compatibility

	_submv usr/bin/ocamldoc\*
	_submv usr/lib/ocaml/ocamldoc
}

_compiler_libs() {
	pkgdesc="Compiler libraries for OCaml"
	depends="$pkgname=$pkgver-r$pkgrel"
	replaces="$pkgname"  # for backward compatibility

	_submv usr/lib/ocaml/compiler-libs
}

runtime() {
	pkgdesc="OCaml runtime environment"
	depends=""
	replaces="$pkgname"  # for backward compatibility

	_submv usr/bin/ocamlrun

	local i; for i in \
		'*.cmo' \
		'*.cmi' \
		'*.cma' \
		'stublibs' \
		'threads/*.cmi' \
		'threads/*.cma'
	do
		_submv "usr/lib/ocaml/$i"
	done
}

_submv() {
	local path="$1"
	mkdir -p "$subpkgdir"/${path%/*}
	mv "$pkgdir"/$path "$subpkgdir"/${path%/*}/
	rmdir -p "$pkgdir"/${path%/*} 2>/dev/null || true
}

sha512sums="
84cd7fd96a4cde5f1063caae112629f37812add4ca2a888c56b3992b8d5528769c2ebc6b1b8f4a0b54e620f8450a7dbe11225f716e0f47cef0d3707457911ac0  ocaml-4.14.0.tar.gz
"
